package com.yupi.yupicturebackend.aop;


import com.fasterxml.jackson.databind.cfg.ContextAttributes;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.UserRoleEnums;
import com.yupi.yupicturebackend.service.UserService;
import org.apache.tomcat.util.descriptor.web.ContextHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class AuthInterceptor {
    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        User loginUser = userService.getLoginInfo(request);
        UserRoleEnums mustRoleEnums = UserRoleEnums.getEnumByValue(mustRole);
        if (mustRoleEnums == null) {
            return joinPoint.proceed();
        }
        UserRoleEnums userRoleEnums = UserRoleEnums.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnums == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //需要管理员权限
        if (UserRoleEnums.ADMIN.equals(mustRoleEnums) && !UserRoleEnums.ADMIN.equals(userRoleEnums)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
